package file

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io"
	"time"
)

type AliConfig struct {
	EndPoint        string `yaml:"end_point"` // 接入点
	AccessKeyID     string `yaml:"access_key_id"`
	AccessKeySecret string `yaml:"access_key_secret"`
	BucketName      string `yaml:"bucket_name"`
	StorageDir string `yaml:"storage_dir"`
	BrowseDir string `yaml:"browse_dir"`
}

type AliStorage struct {
	AliConfig
}

func (s *AliStorage) Path(name string) (storage, browse string) {
	date := time.Now().Format("20060102")
	name = date+"/"+name
	return s.StorageDir+name, s.BrowseDir+name
}

func (s *AliStorage) Save(path string, reader io.Reader) (err error) {
	client, err := oss.New(s.EndPoint, s.AccessKeyID, s.AccessKeySecret)
	if err != nil {
		return err
	}

	// 获取存储空间。
	bucket, err := client.Bucket(s.BucketName)
	if err != nil {
		return err
	}

	if err = bucket.PutObject(path, reader); err != nil {
		return err
	}
	return nil
}

func NewAliStorage(c AliConfig) *AliStorage {
	return &AliStorage{AliConfig:c}
}